package com.sunkq.jvm;

import java.util.concurrent.atomic.AtomicInteger;

class Mynumber{
    volatile int num = 0;

    public void addTo1205(){
        this.num = 1205;
    }

    public void addPlusPlus(){
        num++;
    }

    AtomicInteger atomicInteger = new AtomicInteger();

    public void addMyAtomic(){
        atomicInteger.getAndIncrement();
    }
}


public class VolatileDemo {
    public static void main(String[] args) {
        Mynumber mynumber =new Mynumber();
        for (int i = 1; i <= 20; i++) {
            new Thread(()->{
                for (int j = 1; j <= 1000; j++) {
                    mynumber.addPlusPlus();
                    mynumber.addMyAtomic();
                }
            },String.valueOf(i)).start();
        }

        while (Thread.activeCount()>2){
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName()+"算出的数字为："+mynumber.num);
        System.out.println(Thread.currentThread().getName()+"算出的数字为："+mynumber.atomicInteger);

    }

    private static void seeOkByVolatile() {
        Mynumber mynumber = new Mynumber();
        new Thread(()->{
            try {
                Thread.sleep(3000);
                mynumber.addTo1205();
                System.out.println(Thread.currentThread().getName()+"数字已经改变了");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        },"AAA").start();

        while (mynumber.num==0){

        }
        System.out.println(Thread.currentThread().getName()+"现程结束");
    }
}
